<!--
  考试列表页面
-->
<template>
  <div class="exam-list">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1>考试管理</h1>
        <p>创建、管理和监控在线考试</p>
      </div>
      <div class="header-right">
        <el-button
          type="primary"
          :icon="Plus"
          @click="createExam"
          v-if="authStore.hasPermission('exam:write')"
        >
          创建考试
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :xs="12" :sm="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon upcoming">
              <el-icon size="24"><Clock /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.upcoming }}</div>
              <div class="stat-label">即将开始</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon ongoing">
              <el-icon size="24"><VideoPlay /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.ongoing }}</div>
              <div class="stat-label">正在进行</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon completed">
              <el-icon size="24"><Check /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.completed }}</div>
              <div class="stat-label">已完成</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon total">
              <el-icon size="24"><DataLine /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.total }}</div>
              <div class="stat-label">总考试数</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 筛选和搜索 -->
    <el-card class="filter-card">
      <el-form :model="filterForm" :inline="true">
        <el-form-item label="考试名称">
          <el-input
            v-model="filterForm.keyword"
            placeholder="搜索考试名称"
            clearable
            style="width: 200px"
            @keyup.enter="loadExams"
          />
        </el-form-item>
        <el-form-item label="考试状态">
          <el-select
            v-model="filterForm.status"
            placeholder="选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="全部" value="" />
            <el-option label="草稿" value="draft" />
            <el-option label="已发布" value="published" />
            <el-option label="进行中" value="ongoing" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="filterForm.date_range"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadExams">
            搜索
          </el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 考试列表 -->
    <el-card class="exam-table-card">
      <el-table
        :data="exams"
        v-loading="loading"
        @sort-change="handleSortChange"
      >
        <el-table-column label="考试名称" min-width="200">
          <template #default="{ row }">
            <div class="exam-name">
              <el-link type="primary" @click="viewExamDetail(row)">
                {{ row.title }}
              </el-link>
              <div class="exam-description">{{ row.description }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="状态" width="100" sortable="custom">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="时间" width="180" sortable="custom">
          <template #default="{ row }">
            <div class="exam-time">
              <div>{{ formatDateTime(row.start_time) }}</div>
              <div class="duration">持续 {{ row.duration }} 分钟</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="参与人数" width="120" align="center">
          <template #default="{ row }">
            <div class="participant-info">
              <div>{{ row.participant_count || 0 }}/{{ row.max_participants || '∞' }}</div>
              <el-progress
                :percentage="getParticipantPercentage(row)"
                :show-text="false"
                :stroke-width="6"
              />
            </div>
          </template>
        </el-table-column>

        <el-table-column label="创建者" width="120">
          <template #default="{ row }">
            {{ row.creator_name }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <!-- 学生操作 -->
              <template v-if="authStore.hasRole('student')">
                <el-button
                  v-if="canTakeExam(row)"
                  text
                  type="primary"
                  size="small"
                  @click="takeExam(row)"
                >
                  参加考试
                </el-button>
                <el-button
                  v-if="canViewResult(row)"
                  text
                  type="success"
                  size="small"
                  @click="viewResult(row)"
                >
                  查看成绩
                </el-button>
              </template>

              <!-- 教师/管理员操作 -->
              <template v-if="authStore.hasRole(['teacher', 'admin'])">
                <el-button
                  text
                  type="primary"
                  size="small"
                  @click="viewExamDetail(row)"
                >
                  详情
                </el-button>
                <el-button
                  v-if="canEditExam(row)"
                  text
                  size="small"
                  @click="editExam(row)"
                >
                  编辑
                </el-button>
                <el-button
                  v-if="canMonitorExam(row)"
                  text
                  type="warning"
                  size="small"
                  @click="monitorExam(row)"
                >
                  监考
                </el-button>
                <el-dropdown trigger="click" @command="(command) => handleExamAction(command, row)">
                  <el-button text size="small">
                    更多<el-icon><ArrowDown /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="publish" v-if="canPublishExam(row)">
                        发布考试
                      </el-dropdown-item>
                      <el-dropdown-item command="start" v-if="canStartExam(row)">
                        开始考试
                      </el-dropdown-item>
                      <el-dropdown-item command="finish" v-if="canFinishExam(row)">
                        结束考试
                      </el-dropdown-item>
                      <el-dropdown-item command="results" v-if="row.status === 'completed'">
                        查看结果
                      </el-dropdown-item>
                      <el-dropdown-item command="export" v-if="row.status === 'completed'">
                        导出成绩
                      </el-dropdown-item>
                      <el-dropdown-item
                        command="delete"
                        divided
                        v-if="canDeleteExam(row)"
                      >
                        删除
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </template>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper" v-if="total > 0">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.page_size"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadExams"
          @current-change="loadExams"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAuthStore } from '@/stores'
import {
  getExaminations,
  publishExamination,
  startExamination,
  finishExamination,
  deleteExamination,
  exportExamResults
} from '@/api/examinations'
import type { Examination } from '@/types'
import {
  Plus,
  Clock,
  VideoPlay,
  Check,
  DataLine,
  ArrowDown
} from '@element-plus/icons-vue'

const router = useRouter()
const authStore = useAuthStore()

// 响应式数据
const loading = ref(false)
const exams = ref<Examination[]>([])
const total = ref(0)

// 统计数据
const stats = reactive({
  upcoming: 0,
  ongoing: 0,
  completed: 0,
  total: 0
})

// 筛选表单
const filterForm = reactive({
  keyword: '',
  status: '',
  date_range: [] as Date[]
})

// 分页和排序
const pagination = reactive({
  page: 1,
  page_size: 20
})
const sortField = ref('')
const sortOrder = ref('')

// 加载考试列表
const loadExams = async () => {
  loading.value = true
  try {
    const params: any = {
      page: pagination.page,
      page_size: pagination.page_size,
      search: filterForm.keyword || undefined,
      status: filterForm.status || undefined
    }

    if (filterForm.date_range && filterForm.date_range.length === 2) {
      params.start_date = filterForm.date_range[0].toISOString()
      params.end_date = filterForm.date_range[1].toISOString()
    }

    if (sortField.value) {
      params.ordering = sortOrder.value === 'ascending'
        ? sortField.value
        : `-${sortField.value}`
    }

    const response = await getExaminations(params)
    exams.value = response.data.results
    total.value = response.data.count

    // 更新统计数据
    updateStats()
  } catch (error) {
    console.error('Failed to load exams:', error)
    ElMessage.error('加载考试失败')
  } finally {
    loading.value = false
  }
}

// 更新统计数据
const updateStats = () => {
  stats.upcoming = exams.value.filter(e => e.status === 'published').length
  stats.ongoing = exams.value.filter(e => e.status === 'ongoing').length
  stats.completed = exams.value.filter(e => e.status === 'completed').length
  stats.total = exams.value.length
}

// 重置筛选
const resetFilter = () => {
  Object.assign(filterForm, {
    keyword: '',
    status: '',
    date_range: []
  })
  pagination.page = 1
  loadExams()
}

// 处理排序变化
const handleSortChange = ({ prop, order }: any) => {
  sortField.value = prop || ''
  sortOrder.value = order || ''
  loadExams()
}

// 查看考试详情
const viewExamDetail = (exam: Examination) => {
  router.push(`/examinations/${exam.id}`)
}

// 创建考试
const createExam = () => {
  router.push('/examinations/create')
}

// 编辑考试
const editExam = (exam: Examination) => {
  router.push(`/examinations/${exam.id}/edit`)
}

// 参加考试
const takeExam = (exam: Examination) => {
  router.push(`/examinations/${exam.id}/take`)
}

// 监考
const monitorExam = (exam: Examination) => {
  router.push(`/examinations/${exam.id}/monitor`)
}

// 查看结果
const viewResult = (exam: Examination) => {
  if (authStore.hasRole('student')) {
    router.push(`/examinations/${exam.id}/result`)
  } else {
    // 教师/管理员查看所有结果
    router.push(`/examinations/${exam.id}?tab=results`)
  }
}

// 处理考试操作
const handleExamAction = async (command: string, exam: Examination) => {
  switch (command) {
    case 'publish':
      await publishExam(exam)
      break
    case 'start':
      await startExam(exam)
      break
    case 'finish':
      await finishExam(exam)
      break
    case 'results':
      viewResult(exam)
      break
    case 'export':
      await exportResults(exam)
      break
    case 'delete':
      await deleteExam(exam)
      break
  }
}

// 发布考试
const publishExam = async (exam: Examination) => {
  try {
    await publishExamination(exam.id)
    ElMessage.success('考试发布成功')
    loadExams()
  } catch (error) {
    console.error('Failed to publish exam:', error)
    ElMessage.error('发布考试失败')
  }
}

// 开始考试
const startExam = async (exam: Examination) => {
  try {
    await startExamination(exam.id)
    ElMessage.success('考试开始成功')
    loadExams()
  } catch (error) {
    console.error('Failed to start exam:', error)
    ElMessage.error('开始考试失败')
  }
}

// 结束考试
const finishExam = async (exam: Examination) => {
  try {
    await finishExamination(exam.id)
    ElMessage.success('考试结束成功')
    loadExams()
  } catch (error) {
    console.error('Failed to finish exam:', error)
    ElMessage.error('结束考试失败')
  }
}

// 导出结果
const exportResults = async (exam: Examination) => {
  try {
    await exportExamResults(exam.id, 'excel')
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('Failed to export results:', error)
    ElMessage.error('导出失败')
  }
}

// 删除考试
const deleteExam = async (exam: Examination) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除考试 "${exam.title}" 吗？此操作不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await deleteExamination(exam.id)
    ElMessage.success('考试删除成功')
    loadExams()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to delete exam:', error)
      ElMessage.error('删除考试失败')
    }
  }
}

// 权限检查
const canTakeExam = (exam: Examination) => {
  return authStore.hasRole('student') && exam.status === 'ongoing'
}

const canViewResult = (exam: Examination) => {
  return authStore.hasRole('student') && exam.status === 'completed'
}

const canEditExam = (exam: Examination) => {
  return authStore.hasPermission('exam:write') &&
         ['draft', 'published'].includes(exam.status) &&
         (exam.creator === authStore.user?.id || authStore.hasRole('admin'))
}

const canMonitorExam = (exam: Examination) => {
  return authStore.hasRole(['teacher', 'admin']) &&
         exam.status === 'ongoing'
}

const canPublishExam = (exam: Examination) => {
  return authStore.hasPermission('exam:write') && exam.status === 'draft'
}

const canStartExam = (exam: Examination) => {
  return authStore.hasPermission('exam:write') && exam.status === 'published'
}

const canFinishExam = (exam: Examination) => {
  return authStore.hasPermission('exam:write') && exam.status === 'ongoing'
}

const canDeleteExam = (exam: Examination) => {
  return authStore.hasPermission('exam:delete') &&
         !['ongoing', 'completed'].includes(exam.status) &&
         (exam.creator === authStore.user?.id || authStore.hasRole('admin'))
}

// 工具函数
const getStatusType = (status: string) => {
  const types: Record<string, string> = {
    draft: 'info',
    published: 'warning',
    ongoing: 'danger',
    completed: 'success',
    cancelled: 'info'
  }
  return types[status] || 'info'
}

const getStatusText = (status: string) => {
  const texts: Record<string, string> = {
    draft: '草稿',
    published: '已发布',
    ongoing: '进行中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return texts[status] || status
}

const formatDateTime = (dateTime: string) => {
  return new Date(dateTime).toLocaleString()
}

const getParticipantPercentage = (exam: Examination) => {
  const count = exam.participant_count || 0
  const max = exam.max_participants || count
  return max > 0 ? Math.round((count / max) * 100) : 0
}

// 页面挂载时加载数据
onMounted(() => {
  loadExams()
})
</script>

<style scoped lang="scss">
.exam-list {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    margin-bottom: 24px;

    .header-left {
      h1 {
        font-size: 28px;
        color: var(--el-text-color-primary);
        margin: 0 0 8px 0;
      }

      p {
        font-size: 14px;
        color: var(--el-text-color-regular);
        margin: 0;
      }
    }

    .header-right {
      display: flex;
      gap: 12px;
    }
  }

  .stats-row {
    margin-bottom: 24px;

    .stat-card {
      .stat-content {
        display: flex;
        align-items: center;

        .stat-icon {
          width: 48px;
          height: 48px;
          border-radius: 8px;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 12px;

          &.upcoming {
            background: var(--el-color-warning-light-9);
            color: var(--el-color-warning);
          }

          &.ongoing {
            background: var(--el-color-danger-light-9);
            color: var(--el-color-danger);
          }

          &.completed {
            background: var(--el-color-success-light-9);
            color: var(--el-color-success);
          }

          &.total {
            background: var(--el-color-primary-light-9);
            color: var(--el-color-primary);
          }
        }

        .stat-info {
          .stat-value {
            font-size: 24px;
            font-weight: bold;
            color: var(--el-text-color-primary);
            margin-bottom: 4px;
          }

          .stat-label {
            font-size: 14px;
            color: var(--el-text-color-regular);
          }
        }
      }
    }
  }

  .filter-card {
    margin-bottom: 24px;
  }

  .exam-table-card {
    .exam-name {
      .exam-description {
        font-size: 12px;
        color: var(--el-text-color-regular);
        margin-top: 4px;
        line-height: 1.4;
      }
    }

    .exam-time {
      .duration {
        font-size: 12px;
        color: var(--el-text-color-placeholder);
        margin-top: 2px;
      }
    }

    .participant-info {
      .el-progress {
        margin-top: 4px;
      }
    }

    .action-buttons {
      display: flex;
      gap: 8px;
      flex-wrap: wrap;
    }

    .pagination-wrapper {
      display: flex;
      justify-content: center;
      margin-top: 24px;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .exam-list {
    .page-header {
      flex-direction: column;
      align-items: stretch;
      gap: 16px;

      .header-right {
        justify-content: flex-start;
      }
    }

    .stats-row {
      .stat-card .stat-content {
        .stat-icon {
          width: 40px;
          height: 40px;
        }

        .stat-info .stat-value {
          font-size: 20px;
        }
      }
    }

    .exam-table-card {
      .action-buttons {
        flex-direction: column;
        align-items: stretch;
      }
    }
  }
}
</style>